package com.chukun.multi.promise;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPReply;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;

/**
 * ftp 上传工具类
 */
public class FTPClientUtil {


    private final FTPClient ftp = new FTPClient();

    private final Map<String, Boolean> dirCreateMap = new HashMap<>();
    // 创建线程池
    private volatile static ThreadPoolExecutor threadPoolExecutor;

    static {
        threadPoolExecutor = new ThreadPoolExecutor(1,
                Runtime.getRuntime().availableProcessors() * 2,
                60,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(1024),
                new ThreadFactory() {
                    @Override
                    public Thread newThread(Runnable r) {
                        Thread t = new Thread(r);
                        t.setDaemon(true);
                        return t;
                    }
        }, new ThreadPoolExecutor.CallerRunsPolicy());
    }

    private FTPClientUtil() { }

    /**
     * 异步方法
     * @param ftpServer
     * @param userName
     * @param pwd
     * @return
     */
    public static Future<FTPClientUtil> newInstance(final String ftpServer, final String userName, final String pwd) {
        Callable<FTPClientUtil> callable = () -> {
            FTPClientUtil self = new FTPClientUtil();
            self.init(ftpServer, userName, pwd);
            return self;
        };
        final FutureTask<FTPClientUtil> task = new FutureTask<>(callable);
        /**
         * 异步执行计算，这里如果调用次数频繁，就是造成大量的线程被创建，
         *  这就导致jvm启动的线程过多，增加了线程调度的负担。
         */
        new Thread(task).start();
        return task;
    }

    /**
     * 异步方法,线程池的方式启动
     * @param ftpServer
     * @param userName
     * @param pwd
     * @return
     */
    public static Future<FTPClientUtil> newInstance02(final String ftpServer, final String userName, final String pwd) {
        Callable<FTPClientUtil> callable = () -> {
            FTPClientUtil self = new FTPClientUtil();
            self.init(ftpServer, userName, pwd);
            return self;
        };
        final FutureTask<FTPClientUtil> task = new FutureTask<>(callable);
        /**
         * 异步执行计算，这里使用线程池，减少线程创建，调度
         */
        threadPoolExecutor.execute(task);
        return task;
    }

    /**
     * ftp客户端相关的信息初始化
     * @param ftpServer
     * @param userName
     * @param pwd
     * @throws Exception
     */
    private void init(String ftpServer, String userName, String pwd) throws Exception {
        FTPClientConfig config = new FTPClientConfig();
        ftp.configure(config);
        int reply;
        ftp.connect(ftpServer);

        System.out.println(ftp.getReplyString());

        reply = ftp.getReply();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            throw new RuntimeException("ftp server refused connection....");
        }
        boolean isOk = ftp.login(userName, pwd);
        if (isOk) {
            System.out.println(ftp.getReplyString());
        } else {
            throw new RuntimeException("fail to login.");
        }

        reply = ftp.cwd("~/subspsync");
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            throw new RuntimeException("ftp fail to change work direction....");
        }

        ftp.setFileType(FTP.ASCII_FILE_TYPE);
    }

    /**
     * 上传文件的方法
     * @param file
     * @throws Exception
     */
    public void upload(File file) throws Exception {
        InputStream dataIn = new BufferedInputStream(new FileInputStream(file), 1024 * 8);
        boolean isOk;
        String dirName = file.getParentFile().getName();
        String fileName = dirName + "/" + file.getName();
        ByteArrayInputStream checkFileInput = new ByteArrayInputStream("".getBytes());

        try {
            if (!dirCreateMap.containsKey(dirName)) {
                ftp.makeDirectory(dirName);
                dirCreateMap.put(dirName, null);
            }
            try {
                isOk = ftp.storeFile(fileName, dataIn);
            } catch (Exception e) {
                throw new RuntimeException("fail to upload ....", e);
            }
            if (isOk) {
                ftp.storeFile(fileName + ".c", checkFileInput);
            } else {
                throw new RuntimeException("fail to upload ...."+ftp.getReplyString());
            }
        } finally {
            dataIn.close();
        }
    }

    /**
     * 断开ftp连接
     */
    public void disconnect() {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException e) {
                // no handler
            }
        }
    }
}
